import { defineStore } from 'pinia';
import request from '../utils/request';
import axios from 'axios';
import { ref } from 'vue';

export const useEmployeeStore = defineStore('employee', {
  state: () => ({
    employees: [],
    total: 0,
    loading: false,
    // 排班相关状态
    schedules: [],
    scheduleTotal: 0,
    scheduleLoading: false,
    allEmployees: ref([]),
    performanceList: [],
    performanceTotal: 0,
    performanceLoading: false
  }),
  actions: {
    // 获取员工列表，支持分页和条件查询
    async fetchEmployees(pageNum = 1, pageSize = 10, searchKeyword = '') {
      this.loading = true;
      try {
        // 支持按姓名或职位模糊查询
        let params = { pageNum, pageSize };
        if (searchKeyword && searchKeyword.trim()) {
          params.name = searchKeyword.trim();
        }
        const response = await request.post('/employee-pet/employee/list', params);
        console.log('员工列表响应:', response);
        if (response && response.code === 200) {
          // 兼容后端返回的 data.data、records、data 为数组的情况，并适配字段
          const adapt = emp => ({
            ...emp,
            certifications: Array.isArray(emp.qualification) ? emp.qualification : (emp.qualification ? [emp.qualification] : []),
            joinDate: emp.entryDate || ''
          });
          if (Array.isArray(response.data?.data)) {
            this.employees = response.data.data.map(adapt);
            this.total = response.data.total || 0;
          } else if (Array.isArray(response.data?.records)) {
            this.employees = response.data.records.map(adapt);
            this.total = response.data.total || 0;
          } else if (Array.isArray(response.data)) {
            this.employees = response.data.map(adapt);
            this.total = response.data.length;
          } else {
            this.employees = [];
            this.total = 0;
          }
          // 兼容 employeeId 字段
          this.employees = this.employees.map(emp => ({
            ...emp,
            employeeId: emp.employeeId ?? emp.id
          }));
        } else if (response && Array.isArray(response)) {
          this.employees = response;
          this.total = response.length;
        } else {
          this.employees = [];
          this.total = 0;
        }
        return response;
      } catch (error) {
        console.error('获取员工列表失败:', error);
        this.employees = [];
        this.total = 0;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 添加员工
    async addEmployee(employee) {
      try {
        console.log('添加员工数据:', employee);
        const response = await request.post('/employee-pet/employee/add', employee);
        console.log('添加员工响应:', response);
        if (response && (response.code === 200 || response.success)) {
          // 添加成功后重新获取列表
          await this.fetchEmployees();
        }
        return response;
      } catch (error) {
        console.error('添加员工失败:', error);
        throw error;
      }
    },

    // 更新员工
    async updateEmployee(id, data) {
      try {
        const updateData = {
          employeeId: id,
          ...data
        };
        console.log('更新员工数据:', updateData);
        const response = await request.post('/employee-pet/employee/update', updateData);
        console.log('更新员工响应:', response);
        if (response && (response.code === 200 || response.success)) {
          // 更新成功后重新获取列表
          await this.fetchEmployees();
        }
        return response;
      } catch (error) {
        console.error('更新员工失败:', error);
        throw error;
      }
    },

    // 删除员工
    async deleteEmployee(id) {
      try {
        // 确保 id 为数字类型且不为空
        const realId = typeof id === 'string' ? Number(id) : id;
        console.log('删除员工ID:', realId);
        // 同时传 employeeId 和 id
        const response = await request.post('/employee-pet/employee/delete', { employeeId: realId, id: realId });
        console.log('删除员工响应:', response);
        if (response && (response.code === 200 || response.success)) {
          // 删除成功后重新获取列表
          await this.fetchEmployees();
        }
        return response;
      } catch (error) {
        console.error('删除员工失败:', error);
        throw error;
      }
    },

    // 设置员工列表（用于本地状态管理）
    setEmployees(list) {
      this.employees = list;
    },

    // 获取排班列表
    async fetchSchedules(params = {}) {
      this.scheduleLoading = true;
      try {
        const defaultParams = {
          pageNum: 1,
          pageSize: 10,
          ...params
        };
        console.log('获取排班列表参数:', defaultParams);
        const response = await request.post('/employee-pet/employee/schedule/list', defaultParams);
        console.log('排班列表响应:', response);

        if (response && response.code === 200) {
          if (response.data && Array.isArray(response.data.data)) {
            this.schedules = response.data.data;
            this.scheduleTotal = response.data.total || 0;
          } else {
            this.schedules = [];
            this.scheduleTotal = 0;
          }
        } else {
          this.schedules = [];
          this.scheduleTotal = 0;
        }
        return response;
      } catch (error) {
        console.error('获取排班列表失败:', error);
        this.schedules = [];
        this.scheduleTotal = 0;
        throw error;
      } finally {
        this.scheduleLoading = false;
      }
    },

    // 批量排班
    async batchSchedule(scheduleData) {
      try {
        console.log('批量排班数据:', scheduleData);
        const response = await request.post('/employee-pet/employee/schedule/batch', scheduleData);
        console.log('批量排班响应:', response);

        if (response && response.code === 200) {
          // 排班成功后重新获取列表
          await this.fetchSchedules();
        }
        return response;
      } catch (error) {
        console.error('批量排班失败:', error);
        throw error;
      }
    },

    // 删除排班
    async deleteSchedule(id) {
      try {
        // 用 DELETE 方法，参数拼接在url上
        const response = await request.delete(`/employee-pet/employee/schedule/delete?id=${id}`);
        if (response && response.code === 200) {
          await this.fetchSchedules();
        }
        return response;
      } catch (error) {
        console.error('删除排班失败:', error);
        throw error;
      }
    },

    // 设置排班列表（用于本地状态管理）
    setSchedules(list) {
      this.schedules = list;
    },

    async fetchAllEmployees() {
      // 假设后端支持 pageSize 很大
      const res = await request.post('/employee-pet/employee/list', { pageNum: 1, pageSize: 10000 })
      this.allEmployees = res.data?.data
    },

    // 获取绩效列表
    async fetchPerformanceList(params = {}) {
      this.performanceLoading = true;
      try {
        const response = await request.post('/employee-pet/employee/performance/list', params);
        if (response && response.code === 200) {
          this.performanceList = (response.data.data || response.data.list || []).map(item => ({
            id: item.id,
            employeeName: item.name,
            orderCount: item.orderCount ?? 0,
            salesAmount: item.salesAmount ?? 0,
            attitudeScore: item.workScore,      // 工作态度得分
            totalScore: item.performance,       // 绩效总分
            status: 'draft'
          }));
          this.performanceTotal = response.data.total || 0;
        } else {
          this.performanceList = [];
          this.performanceTotal = 0;
        }
        return response;
      } catch (error) {
        this.performanceList = [];
        this.performanceTotal = 0;
        throw error;
      } finally {
        this.performanceLoading = false;
      }
    },

    // 更新绩效
    async updatePerformance(data) {
      return await request.post('/employee-pet/employee/performance/update', data);
    },

    // 删除绩效
    async deletePerformance(id) {
      return await request.post('/employee-pet/employee/performance/delete', { id });
    }
  }
}); 
